package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class  ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
//       /缓存穿透
//        Shop shop = queryWithPassThrough(id);


        //缓存击穿
        Shop shop = queryWithMutex(id);

        //逻辑过期解决缓存击穿
//        Shop shop = queryWithLogicalExpire(id);

        return Result.ok(shop);
    }


    private static final ExecutorService CACHE_REBUILD_EXECUTOR =
            Executors.newFixedThreadPool(10);
    private Shop queryWithLogicalExpire(Long id) {
        //1 查询redis是否存在
        String shopJson = stringRedisTemplate.opsForValue()
                .get(RedisConstants.CACHE_SHOP_KEY + id);
        //2 不存在直接返回
        if(shopJson == null){
            System.out.println("商铺缓存不存在！");
            return null;
        }
        //3 存在 判断缓存是否过期
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //4 未过期直接返回
        if(expireTime.isAfter(LocalDateTime.now())){
            return shop;
        }
        //5 过期 尝试获取锁修改缓存
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //6 未获取 返回过期数据
        if(!isLock){
            System.out.println("未获取到锁");
            return shop;
        }
        //7 获取到 开启独立线程修改缓存
        CACHE_REBUILD_EXECUTOR.submit(() -> {
            try{
                saveShop2Redis(id, 20L);
            }catch (Exception e){
                throw new RuntimeException(e);
            }finally {
                //9 释放锁
                unLock(lockKey);
            }
        });
        //8 返回数据
        return shop;

    }

    public void saveShop2Redis(Long id, Long expireSeconds){
        //查询数据库
        Shop shop = getById(id);
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 写入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id,
                JSONUtil.toJsonStr(redisData));
    }

    private Shop queryWithMutex(Long id){
        //1 判断缓存是否存在
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(shopJson)){
            //2 存在 返回数据
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //3 不存在
        String lock = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;
        try{
            //3.1 获取互斥锁
            if(!tryLock(lock)){
                //3.2 获取不到
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //3.3 获取到
            //4 根据id查询数据库
            shop = getById(id);
            Thread.sleep(50);
            if(shop == null){
                stringRedisTemplate.opsForValue().set(key, "",
                        RedisConstants.CACHE_NULL_TTL, TimeUnit.SECONDS);
                return null;
            }
            //5  添加缓存
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop),
                    RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            //6 释放锁
            unLock(lock);
        }

        //7 返回
        return shop;
    }
    private Shop queryWithPassThrough(Long id){
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //1 从redis查询店铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2 存在直接返回
        if(StrUtil.isNotBlank(shopJson)){
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        //shopJson == ""   空字符串判断
        if(shopJson != null){
            return null;
        }
        //3 不存在到数据库查询
        Shop shop = getById(id);

        //4 数据库不存在报错
        if(shop == null){
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //5 存在写入redis缓存
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop),
                RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //6 返回店铺信息

        return shop;

    }

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue()
                .setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺不存在！");
        }
        //1 更新数据库
        updateById(shop);
        //2 删除缓存
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        stringRedisTemplate.delete(key);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1 判断是否需要坐标查询
        if(x == null || y == null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }

        //2 查询redis 按照举例排序，分页 结果是shopId， 距离
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        //3 解析id
        GeoResults<RedisGeoCommands.GeoLocation<String>> search = stringRedisTemplate.opsForGeo().search(key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs()
                        .includeDistance().limit(end));
        //4 截取出from end部分
        if(search == null){
            return Result.ok(Collections.emptyList());
        }
        //5 根据id查询shop

        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = search.getContent();
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        if(list.size() <= from){
            return Result.ok(Collections.emptyList());
        }
        list.stream().skip(from).forEach(result ->{
            //获取店铺id
            String shopIdStr = result.getContent().getName();
            //获取距离
            Distance distance = result.getDistance();
            ids.add(Long.valueOf(shopIdStr));
            distanceMap.put(shopIdStr, distance);
        });
        //根据id查询
        String idsStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids)
                .last("order by field(id, " + idsStr + ")").list();
        //6 封装shop中的距离
        for(Shop shop : shops){
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }
}
